/*
 * Copyright (c) 2012-2014, EpicSaaS Yuan Xin technology Co., Ltd.
 * 
 * All rights reserved.
 */
package com.epicsaas.app.ksdapp.interceptor;

import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.epicpaas.sdk.core.api.ServiceResult;
import com.epicpaas.sdk.core.api.logging.Logger;
import com.epicpaas.sdk.core.api.logging.LoggerFactory;
import com.epicsaas.api.tenant.Tenants;
import com.epicsaas.common.Constants;
import com.epicsaas.framework.util.Strings;
import com.epicsaas.service.biz.session.service.ISessionService;
import com.epicsaas.service.biz.userbase.dto.PlatformSession;

/**
 * 从会话中获取用户的租户信息并调用租户 API 设置租户运行时上下文.
 * 
 * @author <a href="http://88250.b3log.org">Liang Ding</a>
 * @version 1.2.0.1, May 28, 2014
 * @since 1.0.1
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {

    /**
     * Logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(TokenInterceptor.class);

    /**
     * 不需要进行校验的URL的正则表达式
     */
    private String pattern;

    public String getPattern() {
        return pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    /**
     * session失效后的拦截机制
     */
    private String redirectURL;

    public String getRedirectURL() {
        return redirectURL;
    }

    public void setRedirectURL(String redirectURL) {
        this.redirectURL = redirectURL;
    }

    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
            throws Exception {
        String tenant = request.getParameter("tenant");
        if (Strings.isBlank(tenant)) {
            tenant = null;
        }

        Tenants.set(tenant);

        if (Strings.isNotBlank(tenant)) {
            return true;
        }

        // 默认使用租户共享
        Tenants.set(Tenants.SHARED_TENANT_NAME);

        if (request.getRequestURI() != null && null != pattern
                && Pattern.compile(pattern).matcher(request.getRequestURI()).matches()) {
            return true;
        }

        final String sessionId = request.getParameter("token");
        if (null == sessionId) {
            if (StringUtils.isNotBlank(redirectURL)) {
                response.sendRedirect(redirectURL + "?goback=" + request.getRequestURL().toString());
            }
            return false;
        }

        //				ServiceResult<PlatformSession> result = sessionService.get(sessionId);
        //				if (result.isSucceed()) {
        //					final PlatformSession session = result.getData();
        //					tenant = (String) session.get(Constants.TENANT);
        //		
        //					Tenants.set(tenant);
        //		
        //					return true;
        //				} else {
        //					LOGGER.warn("获取会话失败", result.getMsg());
        //		
        //					if (StringUtils.isNotBlank(redirectURL)) {
        //						response.sendRedirect(redirectURL + "?goback="
        //								+ request.getRequestURL().toString());
        //					}
        //		
        //					return false;
        //				}
        return true;
    }

}
